package web.controllers;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;

import map.beans.EmpResponseBean;
import map.beans.JqgridResponse;
import map.beans.WmsServerBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import web.service.interfaces.WmsServiceInterface;

@Controller
@RequestMapping("/admin/map")
public class WmsController {
	private static Logger LOGGER = LoggerFactory.getLogger(WmsController.class);
	
	@Autowired
	WmsServiceInterface wmsManager;
	
	@RequestMapping(value = "/records", method = RequestMethod.GET)
	@ResponseBody
	@SuppressWarnings("unused")
	public JqgridResponse<WmsServerBean> records(@RequestParam("_search") Boolean search,
			@RequestParam(value = "filters", required = false) String filters,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sidx,
			@RequestParam(value = "sord", required = false) String sord) {
		JqgridResponse<WmsServerBean> response = null;
		Pageable pageRequest = new PageRequest(page - 1, rows);
		
		try {
			if (sord != null) {
				Sort sort = null;
				sort = new Sort((sord.equals("asc") ? Direction.ASC : Direction.DESC), sidx);
				pageRequest = new PageRequest(page - 1, rows, sort);
				
			} else {
				pageRequest = new PageRequest(page - 1, rows);
			}

			List<WmsServerBean> mapServerDtos = wmsManager.findAll(); //propertiesFileService.getMapServers();

			response = new JqgridResponse<WmsServerBean>();
			response.setRows(mapServerDtos);
			response.setRecords(Integer.valueOf(mapServerDtos.size()).toString());
			response.setTotal(Integer.valueOf(1).toString());// pages total
			response.setPage(Integer.valueOf(1).toString());
			
		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());

        }
		
        return response;
    }
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/wms/reorder", method = RequestMethod.POST)
	@ResponseBody
	public EmpResponseBean reorderWmsServers(@Context HttpServletRequest request) {
		List<WmsServerBean> mapServerDtos = null;
		EmpResponseBean resp = new EmpResponseBean();

		try {
			HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
			Enumeration<String> ids = request.getParameterNames();
			while (ids.hasMoreElements()) {
				String id = ids.nextElement();
				String val = request.getParameterValues(String.valueOf(id))[0];
				map.put(Integer.valueOf(id), Integer.valueOf(val));
			}
			
			wmsManager.reorderWmsServers(map);
			mapServerDtos = wmsManager.findAll();

			if (mapServerDtos == null || mapServerDtos.isEmpty()) {
				resp.setStatus("Failure");
			} else {
				resp.setStatus("Success");
			}
			resp.setResult(mapServerDtos);

		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
		}
		return resp;
	}
	
	@RequestMapping(value = "/wms/servers", method = RequestMethod.GET)	
	public @ResponseBody String getWmsServers() {
		String json = "";

		try {
			json = wmsManager.getMapServersAsJson();

		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
		}

		return json;
	}
	
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@ResponseBody
	public EmpResponseBean create(@RequestParam long urlId, @RequestParam String name, @RequestParam String serverUrl, @RequestParam String type, @RequestParam boolean active, @RequestParam Integer position) {		
		WmsServerBean wmsServer = new WmsServerBean(urlId, name, serverUrl, type, active, position);
		Long result = wmsManager.save(wmsServer);
		
		EmpResponseBean resp = new EmpResponseBean();
		String status = (result != null) ? "Success" : "Failed";
		resp.setStatus(status);
		
		wmsServer.setUrlId(result);
		resp.setResult(wmsServer);
		
		return resp;
	}
	
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public EmpResponseBean update(@RequestParam long urlId, @RequestParam String name, @RequestParam String serverUrl, @RequestParam String type, @RequestParam boolean active, @RequestParam Integer position) {		 
		WmsServerBean wmsServer = new WmsServerBean(urlId, name, serverUrl, type, active, position);		
		Long result = wmsManager.update(wmsServer);

		EmpResponseBean resp = new EmpResponseBean();
		String status = (result != null) ? "Success" : "Failed";
		resp.setStatus(status);
		wmsServer.setUrlId(result);
		resp.setResult(wmsServer);
		
		return resp;
	}	
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public EmpResponseBean delete(@RequestParam long id, @RequestParam String oper, @RequestParam Long... serverUrl) {
		WmsServerBean wms = null;
		EmpResponseBean resp = new EmpResponseBean();
		
		try {							
			for (Long i : serverUrl) {
				wms = wmsManager.getWmsServer(i);
				resp.setResult(wmsManager.delete(wms));
			}
		} catch (Exception e) {
			LOGGER.error("Delete operation on " + wms.getServerUrl() + " not successful");
		}
		
		return resp;
	}
	
	
	
	
	
	
	
	
	
	@RequestMapping(value="/msgs/{msg}", method = RequestMethod.GET)
	@ResponseBody
	public String getMessage(HttpServletRequest request, @PathVariable String msg) {
		LOGGER.debug(msg + "\n\n");
		
		return msg;
	}

}
